package org.nanyuan.forum.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.nanyuan.forum.common.AppResult;
import org.nanyuan.forum.common.ResultCode;
import org.nanyuan.forum.config.AppConfig;
import org.nanyuan.forum.model.Message;
import org.nanyuan.forum.model.User;
import org.nanyuan.forum.service.IMessageService;
import org.nanyuan.forum.service.IUserService;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private IMessageService messageService;

    @Resource
    private IUserService userService;

    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @RequestParam("content") @NonNull String content) {

        //获取当前登录用户的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验当前登录用户的禁言状态
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //不能给自己发
        if (user.getId().equals(receiveUserId)) {
            return AppResult.failed("不能给自己发站内信");
        }
        //检查接收者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() == 1) {
            return AppResult.failed("接收者状态异常");
        }
        //封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());   //发送者id
        message.setReceiveUserId(receiveUserId);  //接收方id
        message.setContent(content);  //站内信内容
        //调用service
        messageService.create(message);
        //返回结果
        return AppResult.success("发送成功");
    }

    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        //获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用service
        Integer count = messageService.selectUnreadCount(user.getId());
        //返回结果
        return AppResult.success(count);
    }
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {

        //获取当前的登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        //返回结果
        return AppResult.success(messages);
    }

    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @Param("id") @NonNull Long id) {
        //查询当前站内信
        Message message = messageService.selectById(id);
        //站内信是否存在
        if (message == null || message.getDeleteFlag() == 1) {
            return AppResult.failed("站内信不存在");
        }
        //站内信是不是自己的
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (!user.getId().equals(message.getReceiveUserId())) {
            //未授权
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //调用service,更新状态为已读
        messageService.updateStateById(id, (byte) 1);
        //返回结果
        return AppResult.success();
    }

    /**
     *
     * @param replyId 要回复的站内信id
     * @param content 内容
     * @return AppResult
     */
    @PostMapping("/reply")
    public AppResult reply (HttpServletRequest request,
                             @RequestParam("replyId") @NonNull Long replyId,
                             @RequestParam("content") @NonNull String content) {
        // 校验当前登录用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 校验要回复的站内信状态
        Message existsMessage = messageService.selectById(replyId);
        if (existsMessage == null || existsMessage.getDeleteFlag() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        // 不能给自己回复
        if (user.getId() == existsMessage.getPostUserId()) {
            // 返回错误描述
            return AppResult.failed("不能回复自己的站内信");
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId()); // 发送者
        message.setReceiveUserId(existsMessage.getPostUserId()); // 接收者
        message.setContent(content); // 内容
        // 调用Service
        messageService.reply(replyId, message);
        // 返回结果
        return AppResult.success();
    }
}
